package cn.fr4nk.crawler.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.fr4nk.crawler.proxy.Proxy;

public class ProxyUtil {

	private static Log log = LogFactory.getLog(ProxyUtil.class);

	public static void main(String[] args) {
		checkProxyJsoup(new Proxy("220.191.12.24", 48530));
	}

	protected static boolean findResult(JSONObject json) {
		Integer status = json.getInteger("status");
		if (null != status && 1 == status) {
			JSONArray data = json.getJSONArray("data");
			if (null != data && 0 < data.size()) {
				Pattern p = Pattern.compile("【(能提供.+)】！！");
				Matcher matcher = p.matcher(data.getString(0));
				if (matcher.find()) {
					log.debug(matcher.group(1));
					return true;
				} else {
					return false;
				}

			}
		}
		log.debug("不提供代理服务");
		return false;
	}

	public static boolean checkProxyJsoup(Proxy proxy) {
		if (null == proxy)
			return false;
		boolean isOk = true;
		try {
			Map<String, String> data = new HashMap<String, String>();
			data.put("data", proxy.getIp());
			data.put("type", "proxycheck");
			data.put("arg", "p=" + proxy.getPort() + "_t=0_o=3");

			Document doc = Jsoup.connect("http://web.chacuo.net/netproxycheck")
					.header("User-Agent",
							"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36")
					.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
					.header("Cookie",
							"__cfduid=asdasd; bdshare_firstime=123123; yjs_id=asdasd; ctrl_time=1; Hm_lvt_ef483ae9c0f4f800aefdf407e35a21b3=123123; Hm_lpvt_ef483ae9c0f4f800aefdf407e35a21b3=12312312")
					.timeout(10000).data(data).post();
			JSONObject res = (JSONObject) JSON.parse(doc.text());
			isOk = findResult(res);
			Thread.sleep(500);
		} catch (IOException | InterruptedException e) {
			log.warn(e);
		}
		return isOk;
	}

	public static boolean checkProxy(Proxy proxy) {
		boolean isOk = false;
		HttpGet method = null;
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		String result = "";
		try {
			httpClient = HttpClients.createDefault();
			method = new HttpGet("http://2017.ip138.com/ic.asp");
			HttpHost proxyHost = new HttpHost(proxy.getIp(), proxy.getPort());
			RequestConfig config = RequestConfig.custom().setProxy(proxyHost).build();
			method.setConfig(config);
			// 执行get请求得到返回对象
			response = httpClient.execute(method);
			// 通过返回对象获取返回数据
			HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			result = EntityUtils.toString(entity);
			Pattern p = Pattern.compile("<center>(.+)</center>");
			Matcher m = p.matcher(result);
			if (m.find()) {
				log.debug("Valid proxy -> " + proxy.getIpPort() + " | " + m.group(1));
				isOk = true;
			}

		} catch (Exception e) {
			log.warn("验证代理[" + proxy.getIpPort() + "]有效线程报错");
			log.warn(e);
		} finally {
			// 关闭资源
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					log.warn(e);
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					log.warn(e);
				}
			}
		}
		return isOk;
	}
}
